package com.evaluation.security;

import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.evaluation.util.RequestUtils;

import cn.hutool.core.lang.UUID;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class AdminInterceptor implements AsyncHandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
		
		String traceId = UUID.fastUUID().toString(true).substring(0, 16);
		String userId = (String) request.getSession().getAttribute("userId");
		
		MDC.put("traceId", traceId);
		MDC.put("uuid", traceId);
		MDC.put("ip", RequestUtils.getIpAddress(request));
		
		String requestUri = request.getRequestURI();
		
		if( userId != null ) {
			MDC.put("userId", userId);
			log.info("[{}]访问{}", userId, requestUri);
		}
		else {
			log.info("自动访问{}", requestUri);
		}
		
		request.setAttribute("requestUri", requestUri);
		
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// Sevlet容器有可能使用线程池，所以必须手动清空线程变量。
		MDC.clear();
	}
}
